﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace UDMBackService
{
    public class MultipartParser
    {
        public Dictionary<string, string> Parameters = new Dictionary<string, string>();
        public List<FilePart> Files = new List<FilePart>();

        public class FilePart
        {
            public string FileName;
            public string ContentType;
            public byte[] Data;
        }

        public bool Parse(HttpListenerRequest request)
        {
            if (!request.ContentType.StartsWith("multipart/form-data"))
                return false;

            // 1. 取边界
            var boundary = request.ContentType.Split(';')
                              .Select(p => p.Trim())
                              .Single(p => p.StartsWith("boundary"))
                              .Split('=')[1].Trim('"');
            var boundaryBytes = Encoding.UTF8.GetBytes("--" + boundary);
            var closeBytes = Encoding.UTF8.GetBytes("--" + boundary + "--");

            // 2. 读完输入流
            var data = new MemoryStream();
            request.InputStream.CopyTo(data);
            var bytes = data.ToArray();

            int pos = 0;
            while (true)
            {
                int idx = IndexOf(bytes, boundaryBytes, pos);
                if (idx == -1) break;
                // 遇到结束边界就停
                if (IndexOf(bytes, closeBytes, idx) == idx) break;

                int next = IndexOf(bytes, boundaryBytes, idx + boundaryBytes.Length);
                if (next == -1) next = bytes.Length;

                // 头与体的分界：连续 4 字节 0D 0A 0D 0A
                int headerEnd = IndexOf(bytes, new byte[] { 13, 10, 13, 10 }, idx) + 4;
                if (headerEnd < 4) { pos = next; continue; }

                // === 解析头部（字符串） ===
                string header = Encoding.UTF8.GetString(bytes, idx + boundaryBytes.Length + 2,
                                                        headerEnd - idx - boundaryBytes.Length - 6);
                bool isFile = header.Contains("filename=");

                // === 体（原始字节） ===
                int bodyStart = headerEnd;
                int bodyLen = next - bodyStart - 2;   // 去掉结尾 \r\n
                if (bodyLen <= 0) { pos = next; continue; }

                byte[] body = new byte[bodyLen];
                Array.Copy(bytes, bodyStart, body, 0, bodyLen);

                if (isFile)
                {
                    var fn = Regex.Match(header, "filename=\"([^\"]*)\"").Groups[1].Value;
                    var ct = Regex.Match(header, "Content-Type: ([^\r\n]+)").Groups[1].Value.Trim();
                    Files.Add(new FilePart
                    {
                        FileName = fn,
                        ContentType = ct,
                        Data = body        // ★ 原始字节，不再转字符串
                    });
                }
                else
                {
                    string name = Regex.Match(header, "name=\"([^\"]*)\"").Groups[1].Value;
                    // 文本字段可以安全转字符串
                    Parameters[name] = Encoding.UTF8.GetString(body);
                }
                pos = next;
            }
            return Files.Count > 0 || Parameters.Count > 0;
        }

        private int IndexOf(byte[] src, byte[] pattern, int start)
        {
            for (int i = start; i <= src.Length - pattern.Length; i++)
            {
                bool ok = true;
                for (int j = 0; j < pattern.Length; j++)
                    if (src[i + j] != pattern[j]) { ok = false; break; }
                if (ok) return i;
            }
            return -1;
        }
    }
}
